package com.zgx.plus.security.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.hutool.json.JSONUtil;
import com.zgx.plus.common.api.model.LoginEntity;
import com.zgx.plus.common.constant.ComConstant;
import com.zgx.plus.common.constant.RedisConstant;
import com.zgx.plus.common.enums.ExceptionEnum;
import com.zgx.plus.common.exception.BizException;
import com.zgx.plus.common.redis.RedisCache;
import com.zgx.plus.common.utils.IpUtils;
import com.zgx.plus.common.utils.SecurityUtils;
import com.zgx.plus.common.utils.ServletUtils;
import com.zgx.plus.security.model.LoginUser;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class TokenService {
    protected Logger log = LoggerFactory.getLogger(getClass());

    @Value("${token.prefix:Bearer }")
    private String prefix;       // 令牌自定义token前缀
    @Value("${token.header:Authorization}")
    private String header;       // 令牌自定义标识
    @Value("${token.secret:zgxyangchangchun}")
    private String secret;      // 令牌秘钥
    @Value("${token.expireTime:30}")
    private int expireTime;      // 令牌有效期（默认30分钟）
    private final long TimeUnitMinutes = 60 * 1000L;      // 1分钟

    @Resource
    private RedisCache redisCache;

    /**
     * 解析request请求中的token信息,并从redis中获取用户的登录信息
     */
    public LoginUser parseToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StrUtil.isNotBlank(token) && token.startsWith(prefix)) {
            token = token.replace(prefix, "");
            String redisLoginUserKey = createRedisLoginUserKey(token);
            log.info("=parseToken={}", JSONUtil.toJsonStr(redisLoginUserKey));
            LoginUser loginUser = redisCache.getCacheObject(redisLoginUserKey);
            log.info("=parseToken={}", JSONUtil.toJsonStr(loginUser));
            return loginUser;
        }
        return null;
    }

    /**
     * @return 解析token中的uuid, 然后再通过uuid去redis中获取存储的用户信息
     */
    private String createRedisLoginUserKey(String token) {
        return StrUtil.concat(true, RedisConstant.REDIS_KEY_LOGIN_USERS,
                StrUtil.toStringOrNull(Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().get(ComConstant.KEY_CLAIM_UUID)));
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息:解析客户端操作系统、浏览器等,设置用户代理信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) {
        JwtBuilder jwtBuilder = Jwts.builder().setClaims(MapUtil.of(ComConstant.KEY_CLAIM_UUID, UUID.fastUUID().toString()));
        String token = jwtBuilder.signWith(SignatureAlgorithm.HS512, secret).compact();
        loginUser.setToken(token);

        UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
        loginUser.setLoginLocation(IpUtils.getRealAddressByIP(IpUtils.getIpAddr(), true));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getPlatform().getName());
        loginUser.setIpaddr(IpUtils.getIpAddr());

        refreshToken(loginUser);
        return token;
    }


    /**
     * 校验token 是否需要刷新
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= expireTime * TimeUnitMinutes / 3) {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新过期时间
     */
    private void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * TimeUnitMinutes);
        redisCache.setCacheObject(createRedisLoginUserKey(loginUser.getToken()), loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * @return 返回登录的用户信息
     */
    public LoginUser getLoginUser() {
        try {
            return (LoginUser) SecurityUtils.getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new BizException(ExceptionEnum.EXCEPTION401);
        }
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (Objects.nonNull(loginUser) && StrUtil.isNotBlank(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }
}
